﻿using B.S.Business.Domain;
using B.S.Business.ErrorCode;
using B.S.Business.Infacetrue;
using B.S.Business.Write.API.Applications.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace B.S.Business.Write.API.Applications.CommandHandler
{
    public class PurchaseDelsCommandHandler : IRequestHandler<PurchaseDelsCommand, ApiResult<string>>
    {
        private readonly IBaseRepository<Purchase> repository;

        public PurchaseDelsCommandHandler(IBaseRepository<Purchase> repository)
        {
            this.repository = repository;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="request">包含要删除的采购记录ID集合的命令对象</param>
        /// <param name="cancellationToken">用于取消操作的令牌</param>
        /// <returns>操作结果的ApiResult对象</returns>
        public async Task<ApiResult<string>> Handle(PurchaseDelsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<string>();

            // 检查请求中的PurchaseId集合是否为空
            if (request.PurchaseId == null || request.PurchaseId.Count == 0)
            {
                result.Code = ApiCode.删除失败;
                result.Msg = "请求的PurchaseId集合为空，无法进行删除操作";
                result.Data = "0";
                return result;
            }

            try
            {
                // 获取要删除的采购记录实体集合
                var entities = await repository.GetAll()
                   .AsTracking()
                   .Where(x => request.PurchaseId.Contains(x.PurchaseId))
                   .ToListAsync(cancellationToken);

                // 遍历实体集合，将未删除的记录标记为已删除
                foreach (var entity in entities)
                {
                    if (!entity.IsDeleted)
                    {
                        entity.IsDeleted = true;
                    }
                }

                // 批量更新这些标记为已删除的实体
                var updatedCount = await repository.UpdateRange(entities);
                var isSuccess = updatedCount > 0;

                result.Code = isSuccess ? ApiCode.删除成功 : ApiCode.删除失败;
                result.Msg = isSuccess ? "删除成功" : "删除失败";
                result.Data = isSuccess ? updatedCount.ToString() : "0";

                return result;
            }
            catch (Exception ex)
            {
                // 记录详细异常信息
                Console.WriteLine($"处理批量删除时发生异常: {ex.Message}，堆栈跟踪: {ex.StackTrace}");
                result.Code = ApiCode.删除失败;
                result.Msg = "处理批量删除时发生异常，删除失败";
                result.Data = "0";
                return result;
            }
        }
    }
}